package org.komarichin.struts2.actions.news;


import org.apache.commons.lang.StringUtils;
import org.komarichin.Constants;
import org.komarichin.beans.IComment;
import org.komarichin.beans.IHasComment;
import org.komarichin.beans.ILanguage;
import org.komarichin.beans.INews;
import org.komarichin.feed.IEntryFeed;
import org.komarichin.feed.IFeedWriter;
import org.komarichin.struts2.BaseAction;
import org.komarichin.struts2.beans.SeoBlank;
import org.komarichin.struts2.beans.models.PageModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: Admin
 * Date: 24.09.2009
 * Time: 13:22:11
 */
public class NewsAction extends BaseAction {
    private static final long serialVersionUID = -133731749260879038L;
    private static final Logger log = LoggerFactory.getLogger(NewsAction.class);

    @Autowired
    private INews<Long> news;

    @Autowired
    private IComment<String> comment;


    private PageModel page = new PageModel();


    @Override
    public String getFeed() throws Exception {
        String basePath = getConfigurator().getServerBasePath();
        List<IEntryFeed> l = new ArrayList<IEntryFeed>();
        for (INews n : getLatestNews()) {
            if (n != null) {
                n.setLink(basePath + "/news/view?news.id=" + n.getId());
                l.add(n);
            }
        }
        String result;
        if (IFeedWriter.FEED_TYPE_RSS.equals(getFeedType())) {
            result = getFeedWriter().getFeeds("News", "/news/archive", "latest news", "rss_2.0", l);
        } else {
            result = getFeedWriter().getFeeds("News", "/news/archive", "latest news", "atom_0.3", l);
        }
        return result;
    }


    /**
     * from parameters passed  object INews without identifier, create news
     *
     * @return {@code com.opensymphony.xwork2.Action.SUCCESS} if created news
     */
    public String save() {
        log.debug("save: {}", news);
        news = getNewsService().save(news);
        if (news != null && news.getId() != null) {
            addActionMessage(getText("news.message.create.success"));
        } else {
            addActionError(getText("news.error.news.not.created"));
        }
        return SUCCESS;
    }

    /**
     * update news. take old news identifier and new value of fields INews's object in request parameters
     *
     * @return {@code com.opensymphony.xwork2.Action.SUCCESS} if updated news
     */
    public String update() {
        log.debug("update: {}", news);
        getNewsService().saveOrUpdate(news);
        return SUCCESS;
    }

    /**
     * get news by identifier, it will passed in request parameters
     *
     * @return {@code com.opensymphony.xwork2.Action.SUCCESS} if news was loaded or {@code com.opensymphony.xwork2.Action.INPUT} if news's identifier is null
     */
    public String load() {
        log.debug("loading news# {}", news);
        if (news != null && news.getId() != null) {
            this.news = getNewsService().findById(news.getId());
            this.news.getDescription();

            defineMetaTags(this.news);

            return SUCCESS;
        } else {
            log.warn("user not choice news id");
            addActionError(getText("news.error.not.choice.news"));
            return INPUT;
        }
    }

    /**
     * delete news. take  news's  identifier  from  request parameters
     *
     * @return {@code com.opensymphony.xwork2.Action.SUCCESS} if delete news or {@code com.opensymphony.xwork2.Action.INPUT} if news's identifier is null
     */
    public String delete() {
        log.debug("delete: {}", news);
        if (news != null && news.getId() != null) {
            news = getNewsService().findById(news.getId());
            getNewsService().remove(news);
            for (IComment comment : getCommentService().getCommentsForObject((IHasComment) news)) {
                getCommentService().remove(comment);
            }
            addActionMessage(getText("news.message.news.removed.success"));
            return SUCCESS;
        } else {
            log.warn("user not choice news id");
            addActionError(getText("news.error.not.choice.news"));
            return INPUT;
        }
    }

    public Collection<INews<Long>> getNewsList() {
        log.debug("get news list#page: " + page);
        defineMetaTags(new SeoBlank(getText("news.list.title"),
                getText("news.list.description"),
                getText("news.list.keyWords"), new Date()));
        if (StringUtils.isNotEmpty(getUserLanguage())) {
            ILanguage lang = getLanguageService().findByName(getUserLanguage());
            if (lang != null) {
                return getNewsService().getNews(lang, page.getStart(), page.getLimit(), page.getField(), page.isOrder());
            }
        }
        return getNewsService().getNews(page.getStart(), page.getLimit(), page.getField(), page.isOrder());
    }

    public Collection<PageModel> getPages() {
        Collection<PageModel> result = new ArrayList<PageModel>();
        int count = 0;
        int limit = page.getLimit();
        if(limit == 0) limit = Constants.DISPLAY_LIMIT;
        count = getNewsService().getCountNews();
        int tt = (int) Math.abs(Math.ceil((double) count / limit));


        for (int t = 0; t < tt; t++) {
            PageModel p = new PageModel();
            p.setName(String.valueOf(t + 1));
            p.setStart(t * limit);
            p.setLimit(limit);
            p.setField(page.getField());
            p.setOrder(page.isOrder());
            result.add(p);
        }
        return result;
    }

    public Collection<INews<Long>> getLatestNews() {
        log.debug("get latest news");
        defineMetaTags(new SeoBlank(getText("news.latest.title"),
                getText("news.latest.description"),
                getText("news.latest.keyWords"), new Date()));
        if (StringUtils.isNotEmpty(getUserLanguage())) {
            ILanguage lang = getLanguageService().findByName(getUserLanguage());
            if (lang != null) {
                return getNewsService().getLatestNews(lang);
            }
        }
        return getNewsService().getLatestNews();
    }

    public INews getNews() {
        return news;
    }


    public Collection<INews<Long>> getAllNews() {
        return getNewsService().getAll();
    }

    public String getCountNews() {
        int result = 0;
        result = getNewsService().getCountNews();
        if (result == 1000) {
            return ">= 1000";
        }
        return String.valueOf(result);
    }

    public int getCurrentPage() {

        if (page.getLimit() == 0) {
            return 0;
        }

        int countNews = getNewsService().getCountNews();
        int countPages = countNews / page.getLimit();


        return 0;
    }

    public String getCountPagesNews() {
        int result = 0;
        result = getNewsService().getCountNews();
        if (result == 1000) {
            return ">= 1000";
        }
        return String.valueOf(result);
    }

    public PageModel getPage() {
        return page;
    }

    public void setPage(PageModel page) {
        this.page = page;
    }


    public String addComment() {
        getCommentService().assignCommentToObject((IHasComment) news, comment);
        return SUCCESS;
    }

    public Collection<IComment<String>> getComments() {
        return getCommentService().getCommentsForObject((IHasComment) news);
    }

    public IComment getComment() {
        return comment;
    }

    public void setComment(IComment comment) {
        this.comment = comment;
    }
}
